package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.CommentApi;
import com.tanhua.api.mongo.PublishApi;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.PublishVo;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.PageBeanVo;
import com.tanhua.template.OssTemplate;
import com.tanhua.utils.RelativeDateFormat;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class QuanziService {

    @Autowired
    private OssTemplate ossTemplate;

    @Reference
    private PublishApi publishApi;

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private CommentApi commentApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    //发布动态
    public ResponseEntity toPublish(Publish publish, MultipartFile[] imageContent) throws IOException {
        //1 获取当前登录用户
        User user = UserHolder.getUser();
        publish.setUserId(user.getId());

        //2 设置审核通过  后期会用华为审核发布的文字和图片是否合法
        publish.setState(0); //审核通过  state: 0 未审核  1 审核通过 2 审核未通过
        //3 上传图片到阿里云oss
        List<String> urlList=new ArrayList<String>();
        if(imageContent!=null){
            for (MultipartFile multipartFile : imageContent) {
                String url = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
                urlList.add(url);
            }
            //设置publish的图片地址
            publish.setMedias(urlList);
        }

        //调用api做保存
        String publishId=publishApi.save(publish);

        //将该动态的id保存到消息中间件中
        rocketMQTemplate.convertAndSend("tanhua-publish",publishId);

        return ResponseEntity.ok(null);
    }

    //我的动态
    public ResponseEntity findMyPublish(Integer page, Integer pagesize, Long userId) {

        // 获取动态数据
        PageBeanVo pbVo = publishApi.findMyPublish(page, pagesize, userId);

        List<Publish> publishList = (List<Publish>) pbVo.getItems();
        // 获取userInfo数据（头像和昵称）
        List<PublishVo> publishVoList=new ArrayList<PublishVo>();
        if(CollectionUtil.isNotEmpty(publishList)){

            for (Publish publish : publishList) {
                //审核结果未通过不进行展示
                if(publish.getState() != 1){
                    continue;
                }
                //创建publishVo进行封装
                PublishVo publishVo = new PublishVo();
                UserInfo userInfo = userInfoApi.findUserInfoVo(publish.getUserId());
                // 将userInfo数据先给publishVo
                BeanUtils.copyProperties(userInfo,publishVo);
                // 手动封装tags
                publishVo.setTags(userInfo.getTags().split(","));
                // 再将publish数据给publishVo
                BeanUtils.copyProperties(publish,publishVo);

                // publishVo.setId(publish.getId().toString());

                // 手动封装id
                publishVo.setId(publish.getId().toString());
                //手动封装时间
                publishVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
                //手动封装距离
                publishVo.setDistance("5.12公里");
                //手动封装图片地址
                List<String> imgList = publish.getMedias();
                if(CollectionUtil.isNotEmpty(imgList)){
                                            //imgList.toArray(new String[]{}) 集合变数组
                    publishVo.setImageContent(imgList.toArray(new String[]{}));
                }
                publishVoList.add(publishVo);
            }
        }

        //PageBeanVo重新封装（PublishVo）
        pbVo.setItems(publishVoList);
        return ResponseEntity.ok(pbVo);
    }

    //我的好友动态
    public ResponseEntity findTimeLinePublish(Integer page, Integer pagesize) {

        // 获取publish数据
        User user = UserHolder.getUser(); //登录用户
        PageBeanVo pbVo = publishApi.findTimeLinePublish(page, pagesize, user.getId());

        List<Publish> items = (List<Publish>) pbVo.getItems();

        List<PublishVo> publishVoList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(items)){
            for (Publish publish : items) {
                //审核结果未通过不进行展示
                if(publish.getState() != 1){
                    continue;
                }
                //获取userInfo
                UserInfo userInfoVo = userInfoApi.findUserInfoVo(publish.getUserId());
                //创建publishVo
                PublishVo publishVo = new PublishVo();
                //封装userInfo
                publishVo.setUserInfo(userInfoVo);
                //封装publish
                publishVo.setPublish(publish);
                /*redis中获取当前用户是否点赞*/
                if(stringRedisTemplate.hasKey(StrUtil.format("publish_like_comment_{}_{}",user.getId(),publish.getId()))){
                    // 设置当前登录用户是否点赞 高亮
                    publishVo.setHasLiked(1);
                }else {
                    publishVo.setHasLiked(0);
                }

                //将每个封装好数据的PublishVo放入publishVoList集合中
                publishVoList.add(publishVo);
            }
        }

        pbVo.setItems(publishVoList);
        return ResponseEntity.ok(pbVo);

    }

    //我的推荐动态
    public ResponseEntity findRecommendPublish(Integer page, Integer pagesize) {
        // 获取publish数据
        User user = UserHolder.getUser();

        //先查redis有大数据给推荐的动态数据
        PageBeanVo pbVo=findFromBigData(UserHolder.getUser().getId(),page,pagesize);
        if(pbVo==null){
            //当前登录用户没有历史行为 大数据每给推荐 还走以前默认的数据即可
            pbVo = publishApi.findRecommendPublish(page, pagesize, user.getId());
        }

        List<Publish> items = (List<Publish>) pbVo.getItems();

        List<PublishVo> publishVoList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(items)){
            for (Publish publish : items) {
                //审核结果未通过不进行展示
                if(publish.getState() != 1){
                    continue;
                }
                //获取userInfo
                UserInfo userInfo = userInfoApi.findUserInfoVo(publish.getUserId());
                //创建publishVo
                PublishVo publishVo = new PublishVo();
                //封装userInfo
                publishVo.setUserInfo(userInfo);

                //封装publish
                publishVo.setPublish(publish);

                /*redis中获取当前用户是否点赞*/
                if(stringRedisTemplate.hasKey(StrUtil.format("publish_like_comment_{}_{}",user.getId(),publish.getId()))){
                    // 设置当前登录用户是否点赞
                    publishVo.setHasLiked(1);
                }else {
                    publishVo.setHasLiked(0);
                }

                if(stringRedisTemplate.hasKey(StrUtil.format("publish_love_comment_{}_{}",user.getId(),publish.getId()))){
                    // 设置当前登录用户是否喜欢
                    publishVo.setHasLoved(1);
                }else {
                    // 设置当前登录用户是否喜欢
                    publishVo.setHasLoved(0);
                }

                publishVoList.add(publishVo);
            }
        }

        pbVo.setItems(publishVoList);
        return ResponseEntity.ok(pbVo);

    }

    //从大数据提供的redis中获取数据
    private PageBeanVo findFromBigData(Long userId, Integer page, Integer pagesize) {
        //先根据key获取当前用户推荐的数据
        String values = stringRedisTemplate.opsForValue().get("QUANZI_PUBLISH_RECOMMEND_" + userId);
        //每查到
        if(StringUtils.isEmpty(values)){
            return null;
        }
        //查到了 21,19,100099,20,28,10064,10020,10006,10003,20007
        String[] pidstr = values.split(",");
        //分页的数据
        int count=pidstr.length; //数组角标的长度就是总条数
        //起始数据
        int start=(page-1)*pagesize;
        if(start>count){
            return null;
        }
        int end=page*pagesize;
        if(end>count){
            end=count;
        }
        // 进行遍历循环 获取每一个publish对象
        List<Publish> list=new ArrayList<>();
        for(int i=start;i<end;i++){
            Publish publish=publishApi.findByPid(Long.parseLong(pidstr[i]));
            list.add(publish);
        }

        return new PageBeanVo(page,pagesize, (long) count,list);

    }

    //点赞
    public ResponseEntity likePublish(String publishId) {

        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setPubType(1); ////评论内容类型： 1-对圈子动态操作 2-对视频操作 3-对评论操作
        comment.setCommentType(1); //评论类型，1-点赞，2-评论，3-喜欢
        Long userId = UserHolder.getUser().getId();
        comment.setUserId(userId);
        //保存
        Integer count = commentApi.save(comment);

        // 去做个redis标记   publish_like_comment_登录用户_给哪个动态点的赞
        stringRedisTemplate.opsForValue().set(StrUtil.format("publish_like_comment_{}_{}",userId,publishId),"1"); //1代表点赞

        return ResponseEntity.ok(count);
    }

    //删除点赞
    public ResponseEntity removeLikePublish(String publishId) {
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setPubType(1); ////评论内容类型： 1-对圈子动态操作 2-对视频操作 3-对评论操作
        comment.setCommentType(1); //评论类型，1-点赞，2-评论，3-喜欢
        Long userId = UserHolder.getUser().getId();
        comment.setUserId(userId);

        //删除
        Integer count = commentApi.remove(comment);

        //redis标记给删除
        stringRedisTemplate.delete(StrUtil.format("publish_like_comment_{}_{}",userId,publishId));

        return ResponseEntity.ok(count);
    }

    //喜欢
    public ResponseEntity lovePublish(String publishId) {

        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setPubType(1); ////评论内容类型： 1-对圈子动态操作 2-对视频操作 3-对评论操作
        comment.setCommentType(3); //评论类型，1-点赞，2-评论，3-喜欢
        Long userId = UserHolder.getUser().getId();
        comment.setUserId(userId);
        //保存
        Integer count = commentApi.save(comment);

        // 去做个redis标记   publish_like_comment_登录用户_给哪个动态点的赞
        stringRedisTemplate.opsForValue().set(StrUtil.format("publish_love_comment_{}_{}",userId,publishId),"1"); //1代表点赞

        return ResponseEntity.ok(count);
    }

    //删除喜欢
    public ResponseEntity removeLovePublish(String publishId) {
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setPubType(1); ////评论内容类型： 1-对圈子动态操作 2-对视频操作 3-对评论操作
        comment.setCommentType(3); //评论类型，1-点赞，2-评论，3-喜欢
        Long userId = UserHolder.getUser().getId();
        comment.setUserId(userId);

        //删除
        Integer count = commentApi.remove(comment);

        //redis标记给删除
        stringRedisTemplate.delete(StrUtil.format("publish_love_comment_{}_{}",userId,publishId));

        return ResponseEntity.ok(count);
    }

    //根据publishId查询publish
    public ResponseEntity findByPublish(String publishId) {

        // publish
        Publish publish = publishApi.findByIdtoPublish(publishId);
        //userInfo
        UserInfo userInfo = userInfoApi.findUserInfoVo(publish.getUserId());
        //封装publishVo
        PublishVo publishVo = new PublishVo();
        publishVo.setUserInfo(userInfo);
        publishVo.setPublish(publish);
        //返回单个publishVo
        return ResponseEntity.ok(publishVo);

    }

    //查询评论列表
    public ResponseEntity findplList(Integer page, Integer pagesize, String publishId) {
        System.out.println(publishId);

        // 查询comment的数据
        PageBeanVo pb = commentApi.findCommentPage(page, pagesize, publishId,1);
        List<Comment> items = (List<Comment>) pb.getItems();

        List<CommentVo> commentVoList=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(items)){
            for (Comment comment : items) {
                // 查询userInfo的数据
                UserInfo userInfo = userInfoApi.findUserInfoVo(comment.getUserId());

                //封装app需要的vo
                CommentVo commentVo = new CommentVo();
                BeanUtils.copyProperties(userInfo,commentVo);
                BeanUtils.copyProperties(comment,commentVo); //评论内容
                commentVo.setCreateDate(RelativeDateFormat.format(new Date(comment.getCreated())));
                commentVoList.add(commentVo);
            }
        }

        pb.setItems(commentVoList);
        //返回
        return ResponseEntity.ok(pb);
    }




    //评论保存
    public ResponseEntity todpl(String publishId, String text) {

        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setPubType(1); ////评论内容类型： 1-对圈子动态操作 2-对视频操作 3-对评论操作
        comment.setCommentType(2); //评论类型，1-点赞，2-评论，3-喜欢
        comment.setContent(text); //评论内容
        Long userId = UserHolder.getUser().getId();
        comment.setUserId(userId);
        //保存
        commentApi.save(comment);

        return ResponseEntity.ok(null);
    }
}
